import './style.scss'
import './servers.js'
import {$,gets} from './common.js'
import {getmusic}from './servers.js'

let flag=false;
const initmusic = async () => {
    // console.log(`aaa`)
  const res = await getmusic()
//   console.log(res)
  $('.left ul').innerHTML=res.data.data.map(item=>{
    return `
        <li data-id="${item.id}">${item.keyTrigger}</li>
        <audio data-id="${item.id}" src=${item.url}></audio>
    `
  }).join('')
 $('.left ul').addEventListener('click', e => {
    if(e.target.nodeName==='LI'){
      if(flag){
      // console.log(e.target.textContent);
    let dataID = e.target.getAttribute('data-id');
    console.log(dataID);
    console.log(res.data.data);

    let newdata = res.data.data.find(item => item.id == dataID);
    console.log(newdata);
    $('.name').innerHTML=newdata.id;
    console.log(newdata.keyTrigger)
    if (newdata){
      let selector = `audio[data-id="${newdata.id}"]`;
      let audio =$(selector);
      if(audio){
        audio.play()
      }
    }
    }
    }
});
document.addEventListener('keydown', e => {
  if(flag){
    console.log(e.key);
  // 找到对应的按键触发数据
  let newdata = res.data.data.find(item => item.keyTrigger === e.key.toUpperCase());
  console.log(newdata);
    $('.name').innerHTML=newdata.id;
  if (newdata) {
    // 创建音频元素
    let audio = new Audio(newdata.url);
    // 播放音频
    audio.play();
  }
  }
});
}
initmusic()

$('.right').addEventListener('click',e=>{
  console.log(e.target)
  if(e.target.className.includes('open')){
    if(e.target.classList.contains('active')){
        e.target.classList.remove('active')
       flag=false;
       $('.name').innerHTML='';
    }else{
        e.target.classList.add('active')
       flag=true;
    }
  }
})
